package com.my.kindlesend.service.impl;

import com.my.kindlesend.entity.FileInfo;
import com.my.kindlesend.entity.UploadFile;
import com.my.kindlesend.enums.FileSendStatusEnum;
import com.my.kindlesend.service.FileInfoService;
import com.my.kindlesend.service.FileUploadService;
import com.my.kindlesend.service.UploadFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件上传服务实现类
 * 处理文件上传的整体业务逻辑，并使用事务管理
 */
@Service
@RequiredArgsConstructor
public class FileUploadServiceImpl implements FileUploadService {

    private final FileInfoService fileInfoService;
    private final UploadFileService uploadFileService;

    /**
     * 上传文件并保存文件信息
     * 包含事务管理，确保文件信息和上传记录数据一致性
     * @param fileInfo 文件信息对象
     * @param userId 用户ID
     * @return 上传文件信息对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UploadFile uploadFile(FileInfo fileInfo, Long userId) {
        // 1. 保存文件信息到FileInfo表
        FileInfo savedFileInfo = fileInfoService.saveFileInfo(fileInfo);
        
        // 2. 创建UploadFile对象并设置状态为未发送
        UploadFile uploadFile = new UploadFile();
        uploadFile.setFileName(savedFileInfo.getFileName());
        uploadFile.setFileInfoId(savedFileInfo.getId());
        uploadFile.setUserInfoId(userId);
        // 设置状态为未发送
        uploadFile.setStatus(FileSendStatusEnum.NOT_SENT.getCode());
        
        // 3. 保存UploadFile信息
        return uploadFileService.saveUploadFile(uploadFile);
    }
}